package com.fone.player.activity.main;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fone.player.ApplicationManage;
import com.fone.player.R;
import com.fone.player.activity.BaseFragmentActivity;
import com.fone.player.activity.personal.PersonalFragment;
import com.fone.player.activity.personal.PlayRecordFragment;
import com.fone.player.activity.personal.PlayRecordFragment.IPlayFragmentCallBack;
import com.fone.player.cache.ImageDownloadModule;
import com.fone.player.client.LoginRst;
import com.fone.player.client.Reporter;
import com.fone.player.client.Reporter.EventId;
import com.fone.player.client.Request;
import com.fone.player.constant.FoneConstant;
import com.fone.player.online.fragment.OnlineFragment;
import com.fone.player.storage.SharedPreferenceModule;
import com.fone.player.util.L;
import com.fone.player.util.RoundImageUtil;
import com.fone.player.util.ScreenUtil;
import com.fone.player.util.StringUtil;
import com.fone.player.view.ExitDialog;
import com.fone.player.view.QuickPlayButton;
import com.fone.player.view.RoundImageView;
import com.fone.player.view.UpdateDialog;

@SuppressLint("HandlerLeak")
public class MainTabActivity extends BaseFragmentActivity implements
		OnClickListener {

	private static final String TAG = "MainTabActivity";
	/** 在线视频 */
	private OnlineFragment mOnlineFragment;
	/** 快速播放 */

	private PlayRecordFragment mPlayFragment;
	/** 我的视频 */
	private PersonalFragment mPersonalFragment;

	private FragmentManager fm;

	private FrameLayout mOnlineLayout;
	private FrameLayout mPersonalLayout;
	public static RoundImageView mPlayLayout;

	public static QuickPlayButton mQuickPlayBtn;

	private FrameLayout frame_content_quick;

	private FragmentTransaction fragmentTransaction;

	private TextView mOnlineText, mMineText;
	private int PERSONALFRAGMENT = 0, ONLINEFRAGMENT = 1,
			QUICKPLAYFRAGMENT = 2;// fragment
									// id
	private int mCurrentFragment = PERSONALFRAGMENT; // 当前fragment
	private int mPreFragment = PERSONALFRAGMENT;// 上一个fragment
	public static String NEWNOTIFICATION = "new_notification";
	public static final int SHOW_UPDATE_DIALOG = 0;
	public static final int CHANGE_MIDBTN_IMAGE = 1;
	public static final int CHANGE_MIDBTN_IMAGE_LOCAL = 2;
	public static final int CHANGE_MIDBTN_IMAGE_DEFAULT = 3;
	public static final int SHOW_QUICK_PLAY_ANIM = 4;

	private int viewMode = 0;
	private static final int ONLINE_FRAGMENT = 0;
	private static final int PLAY_FRAGMENT = 1;
	private static final int PERSONAL_FRAGMENT = 2;

	private Handler mHandler;
	private boolean isCancel = false;
	private boolean isRun = false;
	private boolean isInitUpdate = false;

	private static MainTabActivity mMainTabActivity;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// StorageModule.getInstance().startAllCache();
		mMainTabActivity = this;
		initHandler();
		initView();
		showOnlineBtn();
		
		
		
		if (Request.getInstance().getNetworkType().equals("wifi")) {
			Toast toast = Toast.makeText(this, "您当前处于wifi网络环境下", Toast.LENGTH_LONG);
			toast.show();
		} else if (Request.getInstance().getNetworkType().length() > 0) {
			Toast toast = Toast.makeText(this, "您当前处于非wifi网络环境下，继续使用可能产生流量", Toast.LENGTH_LONG);
			toast.show();
		}
		
		
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (viewMode == ONLINE_FRAGMENT) {
			// 仅在在线视频界面处理升级
			if (!isRun && !isInitUpdate) {
				initUpdate();
			}
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		// 押后台 取消定时器任务
		L.v("测试", "取消计时器");
		isCancel = true;
		isInitUpdate = false;
	}

	private void initHandler() {
		mHandler = new Handler(Looper.getMainLooper()) {

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case SHOW_UPDATE_DIALOG:
					new UpdateDialog(mContext, MainTabActivity.this,
							FoneConstant.loginRst.softupdate.updatedesc,
							UpdateDialog.FORCE, FoneConstant.loginRst);
					isInitUpdate = false;
					break;
				case CHANGE_MIDBTN_IMAGE:

					String url = (String) msg.obj;
					ImageDownloadModule.getInstance().download(url,
							R.drawable.home_quick_play_surface,
							MainTabActivity.mPlayLayout);
					
					SharedPreferenceModule.getInstance().setBoolean("play_record_local_url", false);
					SharedPreferenceModule.getInstance().setString("play_record_url", url);
					SharedPreferenceModule.getInstance().setInt("play_record_progress", msg.arg1);
					
					mQuickPlayBtn.setProgress(msg.arg1);

					break;
				case CHANGE_MIDBTN_IMAGE_LOCAL:
					String uri = (String) msg.obj;
					int width = ScreenUtil.getScreenWidthPix(ApplicationManage
							.getGlobalContext());
					int height = ScreenUtil.dp2px(284);
					mPlayLayout.setImageBitmap(BitmapFactory.decodeResource(
							mContext.getResources(),
							R.drawable.default_image_bg));
					ImageDownloadModule.getInstance().display(uri, width,
							height, mPlayLayout);
					
					SharedPreferenceModule.getInstance().setBoolean("play_record_local_url", true);
					SharedPreferenceModule.getInstance().setString("play_record_url", uri);
					SharedPreferenceModule.getInstance().setInt("play_record_progress", msg.arg1);
					
					mQuickPlayBtn.setProgress(msg.arg1);
					
					break;
				case CHANGE_MIDBTN_IMAGE_DEFAULT:
//					Bitmap roundBitmap = RoundImageUtil.toRoundBitmap(BitmapFactory.decodeResource(mContext.getResources(),
//							 	R.drawable.home_quick_play_surface_default));
//					MainTabActivity.mPlayLayout.setImageBitmap(roundBitmap);
					
					MainTabActivity.mPlayLayout
					   .setBackgroundResource(R.drawable.home_quick_play_surface_default);
					
					SharedPreferenceModule.getInstance().setBoolean("play_record_local_url", true);
					SharedPreferenceModule.getInstance().setString("play_record_url", "");
					SharedPreferenceModule.getInstance().setInt("play_record_progress", 0);
					
					mQuickPlayBtn.setProgress(msg.arg1);
					
					break;
				case SHOW_QUICK_PLAY_ANIM:
					mQuickPlayBtn.StartAnimation();
					break;

				default:
					break;
				}
			}
		};
		
		mHandler.sendEmptyMessageDelayed(SHOW_QUICK_PLAY_ANIM, 1000);
	}

	/**
	 * 初始化版本升级
	 * 
	 * @return void
	 */
	private void initUpdate() {
		L.v("测试", "升级走了:");
		isCancel = false;
		isInitUpdate = true;
		if (null != FoneConstant.loginRst) {
			L.v("测试",
					"FoneConstant.loginRst非空 "
							+ FoneConstant.loginRst.toString());

			LoginRst rst = FoneConstant.loginRst;

			if (null != rst.softupdate) {
				if (FoneConstant.UPDATE_HOME == rst.softupdate.position) {
					if (FoneConstant.FORCE_UPDATE
							.equals(rst.softupdate.updateflag)) {
						isRun = true;
						new UpdateDialog(mContext, this,
								rst.softupdate.updatedesc, UpdateDialog.FORCE,
								rst);
						isInitUpdate = false;
					} else if (FoneConstant.SUGGEST_UPDATE
							.equals(rst.softupdate.updateflag)
							&& FoneConstant.isUpdate == false) {
						// 比较时间,判断是否需要弹框
						if ((System.currentTimeMillis() - SharedPreferenceModule
								.getInstance().getLong(
										FoneConstant.LAST_UPDATA_TIME_SP, 0)) < rst.softupdate.hitday
								* 24 * 60 * 60 * 1000) {
							return;
						}
						int time = 0;
						if (!"".equals(rst.softupdate.t)) {
							if (null != rst.softupdate
									&& null != rst.softupdate.t)
								time = Integer.valueOf(rst.softupdate.t);
						}

						final int runnableTime = time;
						final long firstTime = System.currentTimeMillis();
						new Thread(new Runnable() {
							@Override
							public void run() {
								isRun = true;
								while (true) {
									if (System.currentTimeMillis() == firstTime
											+ runnableTime * 1000) {
										L.v("测试", "到时间! 发消息 中断");
										mHandler.sendEmptyMessage(SHOW_UPDATE_DIALOG);
										isRun = false;
										break;
									}
									if (isCancel) {
										L.v("测试", "取消 中断");
										isRun = false;
										break;
									}
									// L.v("测试", "等待");
								}

							}
						}).start();

					} else {
						L.v(TAG, "initUpdate",
								"homepage update no need to update; foneconstant flag="
										+ FoneConstant.isUpdate);
					}
				}
			}

		}

	}

	private void initView() {
		L.v(TAG, "initView", "----initView: start----");
		fm = getSupportFragmentManager();

		frame_content_quick = (FrameLayout) findViewById(R.id.frame_content_quick);

		mOnlineLayout = (FrameLayout) findViewById(R.id.layout_online);
		mPlayLayout = (RoundImageView) findViewById(R.id.main_middle_iv);
		mPersonalLayout = (FrameLayout) findViewById(R.id.layout_personal);

		mQuickPlayBtn = (QuickPlayButton) findViewById(R.id.main_quick_play_btn);

		mOnlineText = (TextView) findViewById(R.id.main_bottom_online);
		mMineText = (TextView) findViewById(R.id.main_bottom_mine);

		mOnlineLayout.setOnClickListener(this);
		// mPlayLayout.setOnClickListener(this);
		mPersonalLayout.setOnClickListener(this);

		mQuickPlayBtn.setOnClickListener(this);

//		@SuppressWarnings("deprecation")
//		Drawable mQuickPlayBg = new BitmapDrawable(
//				RoundImageUtil.toRoundBitmap(RoundImageUtil
//						.getBitmapFromResources(this,
//								R.drawable.home_quick_play_surface_default)));
//
//		mPlayLayout.setBackgroundDrawable(mQuickPlayBg);
		
		MainTabActivity.mPlayLayout
		   .setBackgroundResource(R.drawable.home_quick_play_surface_default);

		mOnlineFragment = OnlineFragment.newInstance();
		mPlayFragment = PlayRecordFragment.newInstance();
		// mPlayFragment.setQuickPlayImageView(mPlayLayout);
		mPersonalFragment = PersonalFragment.newInstance();
		mPlayFragment.setCallBack(new IPlayFragmentCallBack() {

			@Override
			public void remove() {
				changeFragment();
			}

			@Override
			public void showOnlineFragment() {
				showOnlineBtn();
			}
		});

		boolean is_play_record_local_url = SharedPreferenceModule.getInstance()
				.getBoolean("play_record_local_url");
		String play_record_url = SharedPreferenceModule.getInstance()
				.getString("play_record_url");
		int progress = SharedPreferenceModule.getInstance().getInt("play_record_progress");
		
		if (!StringUtil.isEmpty(play_record_url)) {

			if (is_play_record_local_url) {
				
				Log.i("MainTabActivity", "play_record_local_url: " + play_record_url);
				
				int width = ScreenUtil.getScreenWidthPix(ApplicationManage
						.getGlobalContext());
				int height = ScreenUtil.dp2px(284);
				mPlayLayout.setImageBitmap(BitmapFactory.decodeResource(
						mContext.getResources(),
						R.drawable.default_image_bg));
				ImageDownloadModule.getInstance().display(play_record_url, width,
						height, mPlayLayout);
				
			} else {
				ImageDownloadModule.getInstance().download(play_record_url,
						R.drawable.home_quick_play_surface,
						MainTabActivity.mPlayLayout);
			}
		}
		
		Log.i("Main", "init progress" + progress); 
		
		mQuickPlayBtn.setInitProgress(progress);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_online:
			showOnlineBtn();
			break;
		case R.id.main_quick_play_btn:
			showPlayBtn();
			break;
		case R.id.layout_personal:
			showPersonalBtn();
			break;
		default:
			break;
		}

	}

	private void showOnlineBtn() {
		if (mCurrentFragment == ONLINEFRAGMENT)
			return;

		L.v(TAG, "showOnlineBtn", "----change into online----");
		viewMode = ONLINE_FRAGMENT;

		changeFragment();

		if (!isRun && !isInitUpdate) {
			initUpdate();
		}

		if (fm.findFragmentById(R.id.frame_content) != mOnlineFragment) {
			// 得到Fragment事务管理器
			fragmentTransaction = fm.beginTransaction();
			mPreFragment = mCurrentFragment;
			mCurrentFragment = ONLINEFRAGMENT;
			fragmentTransaction.replace(R.id.frame_content,
					OnlineFragment.newInstance());
			fragmentTransaction.commitAllowingStateLoss();

			mPlayLayout.setImageResource(R.drawable.home_quick_play_surface);
			mOnlineText.setTextColor(getResources().getColor(
					R.color.main_bottom_text_clicked_color));
			mMineText.setTextColor(getResources().getColor(
					R.color.main_bottom_text_unclick_color));

			// 修改点击文字图片变化
			Drawable drawableLeft = getResources().getDrawable(
					R.drawable.home_bottom_online_click);
			drawableLeft.setBounds(0, 0, drawableLeft.getMinimumWidth(),
					drawableLeft.getMinimumHeight());
			mOnlineText.setCompoundDrawables(drawableLeft, null, null, null);
			Drawable drawableRight = getResources().getDrawable(
					R.drawable.home_bottom_mine);
			drawableRight.setBounds(0, 0, drawableRight.getMinimumWidth(),
					drawableRight.getMinimumHeight());
			mMineText.setCompoundDrawables(drawableRight, null, null, null);
		}

	}

	private void showPersonalBtn() {
		if (mCurrentFragment == PERSONALFRAGMENT)
			return;

		viewMode = PERSONAL_FRAGMENT;

		changeFragment();

		L.v("测试", "取消计时器");
		isCancel = true;
		Reporter.logEvent(EventId.CLICK_MY_VEDIO_BTN);
		L.v(TAG, "showPersonalBtn", "----change into personal----");

		if (fm.findFragmentById(R.id.frame_content) != mPersonalFragment) {
			// 得到Fragment事务管理器
			fragmentTransaction = fm.beginTransaction();
			mPersonalFragment = PersonalFragment.newInstance();
			fragmentTransaction.replace(R.id.frame_content, mPersonalFragment);
			fragmentTransaction.commitAllowingStateLoss();
			mPreFragment = mCurrentFragment;
			mCurrentFragment = PERSONALFRAGMENT;
			mPlayLayout.setImageResource(R.drawable.home_quick_play_surface);
			mOnlineText.setTextColor(getResources().getColor(
					R.color.main_bottom_text_unclick_color));
			mMineText.setTextColor(getResources().getColor(
					R.color.main_bottom_text_clicked_color));

			Drawable drawableLeft = getResources().getDrawable(
					R.drawable.home_bottom_online);
			drawableLeft.setBounds(0, 0, drawableLeft.getMinimumWidth(),
					drawableLeft.getMinimumHeight());
			mOnlineText.setCompoundDrawables(drawableLeft, null, null, null);
			Drawable drawableRight = getResources().getDrawable(
					R.drawable.home_bottom_mine_click);
			drawableRight.setBounds(0, 0, drawableRight.getMinimumWidth(),
					drawableRight.getMinimumHeight());
			mMineText.setCompoundDrawables(drawableRight, null, null, null);
		}
	}

	private void showPlayBtn() {
		Reporter.logEvent(EventId.CLICK_QUICK_PLAY_BTN);
		if (mCurrentFragment != QUICKPLAYFRAGMENT) {
			
			Reporter.logEvent(EventId.QUICK_PLAY_ENTRY);

			frame_content_quick.setVisibility(View.VISIBLE);
			viewMode = PLAY_FRAGMENT;
			L.v("测试", "取消计时器");
			isCancel = true;
			L.v(TAG, "showPlayBtn", "----change into quickPlay----");
			if (mCurrentFragment == QUICKPLAYFRAGMENT) {
				return;
			}
			if (fm.findFragmentById(R.id.frame_content_quick) != mPlayFragment) {
				// 得到Fragment事务管理器
				fragmentTransaction = fm.beginTransaction();
				fragmentTransaction.setCustomAnimations(R.anim.bounce_up, 0, 0,
						R.anim.push_down_out);
				fragmentTransaction.replace(R.id.frame_content_quick,
						mPlayFragment);
				fragmentTransaction.commitAllowingStateLoss();
				mPreFragment = mCurrentFragment;
				mCurrentFragment = QUICKPLAYFRAGMENT;
				mPlayLayout
						.setImageResource(R.drawable.home_quick_play_surface_click);
				mOnlineText.setTextColor(getResources().getColor(
						R.color.main_bottom_text_unclick_color));
				mMineText.setTextColor(getResources().getColor(
						R.color.main_bottom_text_unclick_color));

				Drawable drawableLeft = getResources().getDrawable(
						R.drawable.home_bottom_online);
				drawableLeft.setBounds(0, 0, drawableLeft.getMinimumWidth(),
						drawableLeft.getMinimumHeight());
				mOnlineText
						.setCompoundDrawables(drawableLeft, null, null, null);
				Drawable drawableRight = getResources().getDrawable(
						R.drawable.home_bottom_mine);
				drawableRight.setBounds(0, 0, drawableRight.getMinimumWidth(),
						drawableRight.getMinimumHeight());
				mMineText.setCompoundDrawables(drawableRight, null, null, null);
			}
		} else {
			mPlayFragment.downOutView();
		}

	}

	// @Override
	// public boolean onKeyDown(int keyCode, KeyEvent event) {
	// if (mCurrentFragment == QUICKPLAYFRAGMENT) {
	// changeFragment();
	// return true;
	// } else {
	// return super.onKeyDown(keyCode, event);
	// }
	// }

	@Override
	public void onBackPressed() {
		if (mCurrentFragment == QUICKPLAYFRAGMENT) {
			changeFragment();
			return;
		} else {
			new ExitDialog(MainTabActivity.this, MainTabActivity.this,
					"是否要退出应用?");

		}

	}

	public boolean changeFragment() {
		if (mCurrentFragment == QUICKPLAYFRAGMENT) {

			fragmentTransaction = fm.beginTransaction();
			// fragmentTransaction.setCustomAnimations(0, R.anim.push_down_out);
			// fragmentTransaction.replace(R.id.frame_content_quick,
			// new BaseFragment());

			fragmentTransaction.remove(mPlayFragment);

			fragmentTransaction.commitAllowingStateLoss();

			frame_content_quick.setVisibility(View.GONE);
			if (mPreFragment == ONLINEFRAGMENT) { // 如果前一页为 ONLINEFRAGMENT

				mCurrentFragment = ONLINEFRAGMENT;

				mPlayLayout
						.setImageResource(R.drawable.home_quick_play_surface);
				mOnlineText.setTextColor(getResources().getColor(
						R.color.main_bottom_text_clicked_color));
				mMineText.setTextColor(getResources().getColor(
						R.color.main_bottom_text_unclick_color));

				// 修改点击文字图片变化
				Drawable drawableLeft = getResources().getDrawable(
						R.drawable.home_bottom_online_click);
				drawableLeft.setBounds(0, 0, drawableLeft.getMinimumWidth(),
						drawableLeft.getMinimumHeight());
				mOnlineText
						.setCompoundDrawables(drawableLeft, null, null, null);
				Drawable drawableRight = getResources().getDrawable(
						R.drawable.home_bottom_mine);
				drawableRight.setBounds(0, 0, drawableRight.getMinimumWidth(),
						drawableRight.getMinimumHeight());
				mMineText.setCompoundDrawables(drawableRight, null, null, null);

				return true;

			} else if (mPreFragment == PERSONALFRAGMENT) { // 如果前一页为
															// PERSONALFRAGMENT

				mCurrentFragment = PERSONALFRAGMENT;

				mPlayLayout
						.setImageResource(R.drawable.home_quick_play_surface);
				mOnlineText.setTextColor(getResources().getColor(
						R.color.main_bottom_text_unclick_color));
				mMineText.setTextColor(getResources().getColor(
						R.color.main_bottom_text_clicked_color));

				// 修改点击文字图片变化
				Drawable drawableLeft = getResources().getDrawable(
						R.drawable.home_bottom_online);
				drawableLeft.setBounds(0, 0, drawableLeft.getMinimumWidth(),
						drawableLeft.getMinimumHeight());
				mOnlineText
						.setCompoundDrawables(drawableLeft, null, null, null);
				Drawable drawableRight = getResources().getDrawable(
						R.drawable.home_bottom_mine_click);
				drawableRight.setBounds(0, 0, drawableRight.getMinimumWidth(),
						drawableRight.getMinimumHeight());
				mMineText.setCompoundDrawables(drawableRight, null, null, null);

				return true;
			}
		}
		return true;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mMainTabActivity = null;
	}

	// 当来新通知时，将我的视频页面的信封添加一个小红点标记
	public void hasNewNotification() {
		boolean hasNewNotification = SharedPreferenceModule.getInstance()
				.getBoolean(NEWNOTIFICATION, false);
		if (hasNewNotification) {
			if (mCurrentFragment == PERSONALFRAGMENT) {// 当前页面在我的视频，更改小信封标记
				if (mPersonalFragment != null) {
					mPersonalFragment.showNewNotificationIcon(true);
				}
			}
		}
	}

	/**
	 * 设置中间按钮图片
	 * 
	 * @param url
	 * @param isLocal
	 *            是否是本地或者缓存视频
	 */
	public static void setRoundButtonImage(String url, boolean isLocal, int progress) {
		L.v(TAG, "setRoundButtonImage", "url : " + url);
		if (mPlayLayout != null && mMainTabActivity != null
				&& mMainTabActivity.mHandler != null) {
			Message msg = mMainTabActivity.mHandler.obtainMessage();
			if(!TextUtils.isEmpty(url)){
				if (isLocal) {
					msg.what = CHANGE_MIDBTN_IMAGE_LOCAL;
				} else {
					msg.what = CHANGE_MIDBTN_IMAGE;
				}
				msg.obj = url;
				msg.arg1 = progress;
				
				Log.i("MainTabActivity", "setRoundButtonImage: progress " +  progress);
				mMainTabActivity.mHandler.sendMessageAtFrontOfQueue(msg);
			}else{//如果url为空  设置默认图片
				msg.what = CHANGE_MIDBTN_IMAGE_DEFAULT;
				msg.obj = null;
				msg.arg1 = 0;
				mMainTabActivity.mHandler.sendMessageAtFrontOfQueue(msg);
			}
		}
	}
}
